//
//  RegisterViewController.m
//  FeiYang
//
//  Created by user on 15/10/12.
//  Copyright © 2015年 feiyang. All rights reserved.
//

#import "RegistViewController.h"
#import "RegistNextViewController.h"

@interface RegistViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property(nonatomic,strong)UITableView  *registTab;

@property(nonatomic,strong)NSArray      *placeHolderArr;
@property (nonatomic,strong) NSTimer    *timer;
@property (nonatomic,assign) int         statusInt;//计数-倒计时

@property(nonatomic,strong)UIButton    *nextBtn;
@property(nonatomic,strong)UIButton    *identifyBtn;//验证码

@property(nonatomic,strong)UILabel     *sepLine;//验证码分割线

@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _statusInt = 30;
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTheNavigationBar];
    [self createUI];
    if (!_placeHolderArr) {
        _placeHolderArr = @[@"请输入手机号",@"请输入验证码"];
    }
    
}

#pragma mark -------------创建导航栏及相关控件
-(void)createTheNavigationBar
{
    
    //    自定义navgationBar
    TopView *topView = [[TopView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 64.0f)];
    [topView setTitile:@"注册"];
    [self.view addSubview:topView];
    
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 35.0f, 49.0f, 16.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnCLick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
}
- (void)backBtnCLick:(UIButton*)btn
{
    [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"" withType:TRUE];
    [self dismissViewControllerAnimated:TRUE completion:^(void){}];
}

-(void)createUI
{
    //    分割线
    
    UILabel *sepLab1 = [[UILabel alloc] initWithFrame:CGRectMake(8.0f, 16.0f+50.0f, SCREEN_WIDTH-16.0f, .5f)];
    sepLab1.backgroundColor = [UIColor hexStringToColor:kColorGraySperator];
    _sepLine = [[UILabel alloc] init];
    
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardhide)];
    tapGesture.cancelsTouchesInView = NO;
    [self.registTab addGestureRecognizer:tapGesture];
    
    [self.registTab addSubview:sepLab1];
    
    [self.view addSubview:self.registTab];
    [self.registTab addSubview:self.nextBtn];
}
-(UITableView *)registTab
{
    if (!_registTab) {
        _registTab = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _registTab.backgroundColor = [UIColor hexStringToColor:kColorBackground];
        _registTab.delegate = self;
        _registTab.dataSource = self;
        _registTab.rowHeight = 50.0f;
        _registTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        
    }
    return _registTab;
}


//验证码按钮
-(UIButton *)identifyBtn
{
    if (!_identifyBtn) {
        _identifyBtn = [[UIButton  alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-88.0f-16.0f,7.0f, 88.0f, 36.0f)];
        [_identifyBtn addTarget:self action:@selector(buttonIdentifyTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_identifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        [_identifyBtn.titleLabel setFont:[UIFont systemFontOfSize:12.0f]];
        _identifyBtn.backgroundColor = [UIColor whiteColor];
        [_identifyBtn setTitleColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
        
//        _identifyBtn.layer.borderWidth = 1;
//        _identifyBtn.layer.borderColor = [[UIColor hexStringToColor:COLOR_VALUE] CGColor];
//        _identifyBtn.layer.cornerRadius = 2.0;
    }
    return _identifyBtn;
}

//下一步按钮
-(UIButton *)nextBtn
{
    if (!_nextBtn) {
        _nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(16.0f,132.0f, SCREEN_WIDTH-32.0f, 44.0f)];
        [_nextBtn addTarget:self action:@selector(buttonNextTapped) forControlEvents:UIControlEventTouchUpInside];
        [_nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
        _nextBtn.layer.cornerRadius = 2;
        _nextBtn.layer.masksToBounds = YES;
        [_nextBtn setBackgroundColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
        
    }
    return _nextBtn;
}

#pragma mark-tableViewDelegate&datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.placeHolderArr.count;
}
static UITextField *__textField;//记录当前的textField
static UITextField *__textFieldPwd;//记录当前的textField
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        
        
        UITextField *userTF = [[UITextField alloc] init];
        userTF.tag = 2000;
        userTF.delegate = self;
        userTF.clearButtonMode = UITextFieldViewModeWhileEditing;
        userTF.keyboardType = UIKeyboardTypeNumberPad;
        userTF.font = [UIFont systemFontOfSize:14.0f];

//        [userTF setValue:[UIFont boldSystemFontOfSize:14.0f] forKeyPath:@"_placeholderLabel.font"];
        [cell.contentView addSubview:userTF];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    
    UITextField *text = (UITextField *)[cell.contentView viewWithTag:2000];
    text.placeholder = [_placeHolderArr objectAtIndex:indexPath.row];
    
    
    if (indexPath.row==0) {
        text.frame = CGRectMake(16.0f, 5.0f, SCREEN_WIDTH-32.0f-16.0f, 45.0f);
        __textField = text;
       
    }
    if (indexPath.row==1) {
        __textFieldPwd = text;
        text.frame = CGRectMake(16.0f, 5.0f, SCREEN_WIDTH-16.0-100.0f-16.0f, 45.0f);
        [cell addSubview:self.identifyBtn];
        _sepLine.frame = CGRectMake(SCREEN_WIDTH-32.0f-88.0f, 15.0f, 1.0f, 25.0f);
        _sepLine.backgroundColor = [UIColor hexStringToColor:kColorGraySperator];
        [cell addSubview:_sepLine];

    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 16.0f;
}




#pragma mark-验证码按钮方法
- (void)buttonIdentifyTapped:(UIButton*)btn
{
    btn.enabled = FALSE;
    
    if (__textField.text.length>0) {
        if ([AccountTools validatePhoneNumber:__textField.text ]==YES) {
            
            //            发送请求
            
            [AppGlobalClass PostDataWithNSstring:CHECKUSERCD withDictionary:@{@"userCd":__textField.text} success:^(NSDictionary *dictionary) {
                if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:NO]])
                {
                    //手机号码未注册过
                    //获取成功开启定时器
                    if (!_timer)
                    {
                        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeCounting) userInfo:nil repeats:TRUE];//开启定时器  倒计时结束后，在倒计时方法内使得按钮可以点击
                        [_timer fire];
                    }

                    [AppGlobalClass PostDataWithNSstring:GETCHECKCODE withDictionary:@{@"mobileNumber":__textField.text} success:^(NSDictionary *dictionary) {
                        
                        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
                        {
                            
                            
                        }
                        else
                        {
                            NSString * str = [dictionary objectForKey:@"message"];
                            ALERT_VIEW(str);

                        }
  
                        
                    } failure:^(NSError *error) {
                        

                    } networkerror:^(NSString *networkerror) {
 
                    }];
                    
                    
                }
                else
                {

                    ALERT_VIEW(@"该手机号码已经注册过");
                    btn.enabled = TRUE;

                    
                }
   
                
            } failure:^(NSError *error) {
                btn.enabled = TRUE;

            } networkerror:^(NSString *networkerror) {
                btn.enabled = TRUE;
  
            }];
            
            
            
        }
        else
        {
            btn.enabled = TRUE;
            ALERT_VIEW(@"手机号不正确");
        }
    }
    else{
        btn.enabled = TRUE;

        ALERT_VIEW(@"手机号不能为空");
    }
}


#pragma mark-下一步按钮方法
-(void)buttonNextTapped
{
       if ([AccountTools isEmpty:__textField.text]==YES) {
        ALERT_VIEW(@"请输入手机号");
        return;
    }
    
    if ([AccountTools isEmpty:__textFieldPwd.text]==YES) {
        
        ALERT_VIEW(@"请输入验证码")
        return;
    }
    if ([AccountTools validatePhoneNumber:__textField.text]==NO) {
        ALERT_VIEW(@"请输入正确的手机号");
        return;
    }
    [[AnimationIndicator sharedIndicator] startAnimation];
    
    [AppGlobalClass PostDataWithNSstring:VALIDATECHECKCODE withDictionary:@{@"mobileNumber":__textField.text,@"checkCode":__textFieldPwd.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            //验证码有效的情况下跳转
            RegistNextViewController *registNextVC = [[RegistNextViewController alloc]init];
            registNextVC.mobile = __textField.text;
            registNextVC.checkCode = __textFieldPwd.text;
            [self presentViewController:registNextVC animated:TRUE completion:^(void){}];
        }else
        {
            NSString * str = [dictionary objectForKey:@"message"];
            ALERT_VIEW(str);
            
        }
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"完成" withType:TRUE];
    } failure:^(NSError *error) {
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"失败" withType:TRUE];

        
    } networkerror:^(NSString *networkerror) {
        
        [[AnimationIndicator sharedIndicator] stopAnimationWithLoadText:@"无网络" withType:TRUE];

    }];
}

-(void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
    
}
//时间倒计时
-(void)timeCounting
{
    
    _identifyBtn.enabled = NO;//点击后，让不可再点击
    
    
    NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
//    [_identifyBtn setBackgroundColor:[UIColor hexStringToColor:@"#000000"] forState:UIControlStateDisabled];
//    _identifyBtn.layer.borderColor = [[UIColor hexStringToColor:@"#000000"] CGColor];
//    _identifyBtn.alpha = 0.3;
    [_identifyBtn setTitleColor:[UIColor hexStringToColor:kColorGray] forState:UIControlStateDisabled];
    
    
    if ([phoneVersion doubleValue] >= 8.0) {
        [_identifyBtn setTitle:[NSString stringWithFormat:@"等待%ds",_statusInt] forState:UIControlStateNormal];
        
    }
    else{
        _identifyBtn.titleLabel.text = [NSString stringWithFormat:@"等待%ds",_statusInt] ;
        _identifyBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    if(_statusInt == 0)
    {
        
        [_identifyBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        _statusInt = 30;
        _identifyBtn.enabled = TRUE;
        _identifyBtn.backgroundColor = [UIColor whiteColor];
        [_identifyBtn setTitleColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal];
//        _identifyBtn.layer.borderColor = [[UIColor hexStringToColor:COLOR_VALUE] CGColor];
        _identifyBtn.alpha = 1;
        [_timer invalidate];
        _timer = nil;
        return;//直接返回
    }
    _statusInt -=1;
    
}

//隐藏键盘
-(void)keyboardhide
{
    [__textFieldPwd resignFirstResponder];
    [__textField resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
